// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

var ProjectList = new function(){
	this.listNode = null;
	this.projects = [];
	this.sortSelection = null;
	this.sortAsc = true;
	this.filterEnded = false;

	this.ascArrow = '▲';
	this.decArrow = '▼';

	/*
	 * Performs all common logic that happens before a sort.
	 */
	this.prepareSort = function(link)
	{
		//Fetch the data
		curSort = ProjectList.sortSelection;
		curAsc = ProjectList.sortAsc;

		//Clear any existing sort arrow
		if(curSort != null)
		{
			$(curSort).html($(curSort).attr('title'));
		}

		//Determine the sort order
		if(link != curSort)
		{
			ProjectList.sortSelection = link;
			ProjectList.sortAsc = true;
		}
		else
		{
			ProjectList.sortAsc = !ProjectList.sortAsc;
		}

		arrow = (ProjectList.sortAsc) ? ProjectList.ascArrow : ProjectList.decArrow;
		title = $(link).attr('title');
		$(link).html(arrow +' '+ title);
	}

	/*
	 * Updates the list, after sorting.
	 */
	this.updateList = function()
	{
		for(i=0; i<ProjectList.projects.length; i++)
		{
			project = ProjectList.projects[i];
			$(project.node).remove();
			$(ProjectList.listNode).append($(project.node));
		}
	}

	this.Project = function(li, pos)
	{
		this.node = li;
		this.name = null;
		this.percentFunded = 0;
		this.isActive = false;
		this.closing = null;
		this.timeLeft = 0;
		this.backed = pos;


		this.name = $(li).find('h2').find('a').html();
		project_classes = $('.project-card', li)[0].className;

		if(project_classes.match(/project-live/))
		{
			this.isActive = true;
			this.percentFunded = $('.project-pledged-percent', li).text().replace(/\s*([\d|,]*)%\s*\w*/, "$1").replace(',', '');

			//Calculate closing date
			timeRemaining = $(li).find('.last').text().replace(/\s*([0-9]+)\s*\w+ to go\s*/, "$1");
			timeUnit = $(li).find('.last').text().replace(/\s*[0-9]*\s*([a-z]+) to go\s*/, "$1");
                                    
			switch (timeUnit)
			{
				case 'days':
				case 'day':
					this.closing = new Date().getTime() + (timeRemaining*24*60*60*1000);
					this.timeLeft = timeRemaining*24*60;
				break;

				case 'hours':
				case 'hour':
					this.closing = new Date().getTime() + (timeRemaining*60*60*1000);
					this.timeLeft = timeRemaining*60;
				break;

				case 'minutes':
				case 'minute':
					this.closing = new Date().getTime() + (timeRemaining*60*1000);
					this.timeLeft = timeRemaining;
				break;
			}
		}
		else if(project_classes.match(/project-successful/))
		{
			this.percentFunded = $('.project-pledged-percent', li).text().replace(/\s*([0-9]+)%\s*\w*/, "$1");

			timeEnded = $(li).find('.last').text().replace(/\s*Funded\s*([a-zA-Z0-9\s]+)\s*\s*/, "$1");
			this.closing = Date.parse(timeEnded);
		}
		else if(project_classes.match(/project-failed/))
		{
			timeEnded = $(li).find('.project-status span').text().replace(/\(([0-9\/\s]+)\)/, "$1");
			this.closing = Date.parse(timeEnded);

			$(li).prepend('<img class="failed" src="" />')
		}
		$(li).attr('closing', this.closing);
		$(li).attr('timeLeft', this.timeLeft);
	}

	this.init = function()
	{
		ProjectLists = $(".project-card-list").each(function(){
			ProjectList.listNode = $(this);

			items = $(this).children('li').each(function(i, item){
				project = new ProjectList.Project(item, i);
				ProjectList.projects.push(project);
			});

			$(this).prepend('<li class="sortable">Sort By:</li>');
			sort_li = $(this).children('li.sortable');

			remain = $('<a class="first" title="Time remaining">Time Remaining <span class="arrow"/></a>');
			$(remain).click(function(){
				var time = new Date().getTime() + (365*24*60*60*1000);
				ProjectList.prepareSort(this);
				ProjectList.projects.sort(function(a, b){

					if(a.timeLeft == 0 && b.timeLeft == 0)
					{
						comp = (ProjectList.sortAsc) ? b.closing - a.closing : a.closing - b.closing;
					}
					else if(a.timeLeft == 0)
					{
						comp = 1;
					}
					else if(b.timeLeft == 0)
					{
						comp = -1;
					}
					else
					{
						comp = (ProjectList.sortAsc) ? a.timeLeft - b.timeLeft : b.timeLeft - a.timeLeft;
					}

					return comp;
				});
				ProjectList.updateList();
			});
			$(sort_li).append(remain);

			ending = $('<a title="Date Added">Date Added <span class="arrow"/></a>');
			$(ending).click(function(){
				ProjectList.prepareSort(this);
				ProjectList.projects.sort(function(a, b){
					return (ProjectList.sortAsc) ? a.closing - b.closing : b.closing - a.closing;
				});
				ProjectList.updateList();
			});
			$(sort_li).append(ending);

			funded = $('<a title="Percent Funded">Percent Funded <span class="arrow"/></a>');
			$(funded).click(function(){
				ProjectList.prepareSort(this);
				ProjectList.projects.sort(function(a, b){
					return (ProjectList.sortAsc) ? a.percentFunded - b.percentFunded : b.percentFunded - a.percentFunded;
				});
				ProjectList.updateList();
			});
			$(sort_li).append(funded);

			backed = $('<a title="Date backed">Date Backed <span class="arrow"/></a>');
			$(backed).click(function(){
				ProjectList.prepareSort(this);
				ProjectList.projects.sort(function(a, b){
					return (ProjectList.sortAsc) ? a.backed - b.backed : b.backed - a.backed;
				});
				ProjectList.updateList();
			});
			$(sort_li).append(backed);

			sort_filter = $(sort_li).prepend('<div class="sort_filter"/>');

			/*
			show_ended = $('<a title="Ended">Hide Ended</a>');
			$(show_ended).click(function(){
				ProjectList.filterEnded = !ProjectList.filterEnded;

				if (ProjectList.filterEnded)
				{
					$('.project-successful').parents('li').css('display', 'none');
					$('.project-failed').parents('li').css('display', 'none');
					$(show_ended).html('Show Ended');
				}
				else
				{
					$('.project-successful').parents('li').css('display', 'list-item');
					$('.project-failed').parents('li').css('display', 'list-item');
					$(show_ended).html('Hide Ended');
				}
			});
			$(sort_filter).append(show_ended);
			*/
		});
		if ($('li.sortable').length > 0)
		{
			$(remain).click();
			$(sort_li).css('display', 'list-item');
		}
	}

	this.swapTab = function(tab)
	{
		$('.menu-tabs li').removeClass('selected');
		$('.menu-tabs li.'+ tab).addClass('selected');

		switch (tab)
		{
			case 'starred':
			$('.project-card-list li:not(.completed))').css('display', 'list-item');
			$('.project-card-list li.completed:not(.sortable)').css('display', 'none');
			break;

			case 'followed':
			$('.project-card-list li.completed').css('display', 'list-item');
			$('.project-card-list li:not(.completed):not(.sortable)').css('display', 'none');
			break;
		}
	}
}

/*
 * Initializes all possibilities for page updates.
 */
var split = null;
$(document).ready(function(){
	if (document.location.href.indexOf('projects/following') > 0)
	{
		$('.project-card-list').find('.project-card.project-successful').parent().parent('li').addClass('completed');
		$('.project-card-list').find('.project-card.project-failed').parent().parent('li').addClass('completed');


		chrome.extension.sendRequest({'action': 'getOption', 'option': 'ksprime-split_projects'},function(response){
			console.log(response);
			if (response == 'true')
			{
				$(".menu-tabs").append('<li class="followed"><a id="project-followed" href="javascript:void(0);">Followed Projects <span class="count">'+ $('.project-card-list .completed').length +'</span></a></li>');
				$('.menu-tabs .followed').prev().addClass('starred').html('<a id="project-starred" href="javascript:void(0);">Starred Projects <span class="count">'+ $('.project-card-list > li:not(.completed)').length +'</span></a>');

				$('#project-followed').click(function(){ProjectList.swapTab('followed');});
				$('#project-starred').click(function(){ProjectList.swapTab('starred');});
				ProjectList.swapTab('starred');
			}
		});
	}
	ProjectList.init();
});